package com.zmjmall.demo.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.zmjmall.demo.api.AddressService;
import com.zmjmall.demo.api.SysAreaService;
import com.zmjmall.demo.dto.AddressDTO;
import com.zmjmall.demo.enums.ResultEnum;
import com.zmjmall.demo.model.SysArea;
import com.zmjmall.demo.util.JsonUtil;
import com.zmjmall.demo.utils.ResultVOUtil;
import com.zmjmall.demo.vo.AddressVO;
import com.zmjmall.demo.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 收货地址控制层
 *
 * @author zmj
 * @version 2018/7/4
 */
@RestController
@RequestMapping("/address")
@Slf4j
public class AddressController {

    @Reference
    private AddressService addressService;

    @Reference
    private SysAreaService sysAreaService;

    /**
     * 省市区code
     * @param id
     * @return
     */
    @GetMapping("/area/{id}")
    @ResponseBody
    @Cacheable(value = "area",key = "#id")
    public ResultVO<SysArea> findById(@PathVariable @RequestParam(value = "id",defaultValue = "0") String id) {
        List<SysArea> areas = sysAreaService.findByParentId(id);
        return ResultVOUtil.success(JsonUtil.toJsonIgnore(areas));
    }

    /**
     * 收货地址列表
     * @param userId
     * @return
     */
    @GetMapping
    @ResponseBody
    public ResultVO findAll(String userId) {
        List<AddressVO> list = addressService.findByUserId(userId);
        if(list.isEmpty()){
            return ResultVOUtil.success(ResultEnum.NOT_ADDRESS);
        }
        return ResultVOUtil.success(JsonUtil.toJsonIgnore(list));
    }

    /**
     * 新增收获地址
     * @param addressDTO
     * @return
     */
    @PostMapping
    @ResponseBody
    public ResultVO createAddress(String userId,@Valid AddressDTO addressDTO) {
        addressDTO.setUserId(userId);
        addressService.save(addressDTO);
        return ResultVOUtil.success(ResultEnum.SUCCESS);
    }

}
